import router from '@/router';
import store from './store';

const whiteList = ['/login'];

router.beforeEach(async (to, from, next) => {
  // 已登录，不允许进入login
  // 未登录，只允许进入login
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/');
    } else {
      // 判断用户资料是否存在，不在，获取用户信息
      if (!store.getters.hasUserInfo) {
        const { permission } = await store.dispatch('user/getUserInfo');
        // 处理用户权限
        const filterRoutes = await store.dispatch(
          'permission/filterRoutes',
          permission.menus
        );
        // 循环添加动态路由
        filterRoutes.forEach((item) => {
          router.addRoute(item);
        });
        // 添加完动态路由，要进行一次主动跳转
        return next(to.path);
      }
      next();
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next();
    } else {
      next('/login');
    }
  }
});
